//
//  ViewController.m
//  JXFile
//
//  Created by 祁俊喜 on 2024/4/1.
//

#import "ViewController.h"
#import "GCDWebServer.h"
#import "GCDWebUploader.h"
#import "GCDWebServerDataResponse.h"
#import "GCDWebServerURLEncodedFormRequest.h"
#import "FilesManage.h"
#import "TableViewCell.h"
#import <JXKitManage/JXKitManage.h>
#import "FileSharing-Swift.h"
#import "SetViewController.h"
#import "ZFNormalViewController.h"
#import <AdSupport/ASIdentifierManager.h>

static NSString *identifier = @"TableViewCell";

@interface ViewController () <GCDWebUploaderDelegate,UITableViewDelegate,UITableViewDataSource,UIDocumentInteractionControllerDelegate,UIDocumentPickerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, strong) GCDWebUploader *webServer;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *fileList;

@property (weak, nonatomic) IBOutlet UILabel *spaceLab;

@property (nonatomic, strong) UIDocumentPickerViewController *documentPickerVC;

@property (weak, nonatomic) IBOutlet UIBarButtonItem *startItem;

@end

@implementation ViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self refreshData];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"小助手";
    
    self.view.backgroundColor = [UIColor systemGroupedBackgroundColor];
    
    [[FilesManage getCurrentWindow] showWatermark];
    
    self.fileList = [NSMutableArray new];
    
    [self addNotification];
    
    [self initWebServer];
    
    [self.view addSubview:self.tableView];
    
    self.spaceLab.text = [FilesManage usedSpaceAndfreeSpace];
    
    [self.view bringSubviewToFront:self.spaceLab];
    
}

- (void)addNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(faceBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(faceEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
}

-(void)faceBecomeActive{
    UIPasteboard *pb = [UIPasteboard generalPasteboard];
    if (pb.string.length > 0) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (self.webServer.isRunning) {
                [self.webServer stop];
            }
            
            [self.webServer start];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (self.webServer.isRunning) {
                    self.webServer.epilogue = [FilesManage htmlStringByAttributeString:pb.string];
                }
                
            });
        });
    }
    [self refreshData];
}

-(void)faceEnterBackground{
    
}

- (void)removeNotification{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
}

- (IBAction)imageItemAction:(UIBarButtonItem *)sender {
    [self openPhoto];
}

- (IBAction)fileItemAction:(UIBarButtonItem *)sender {
    [self presentViewController:self.documentPickerVC animated:YES completion:nil];
}

- (IBAction)rightItemAction:(UIBarButtonItem *)sender {
    
    if ([self.webServer isRunning]) {
        [self.webServer stop];
        self.startItem.title = @"开启";
        self.startItem.image = [UIImage systemImageNamed:@"tv.badge.wifi"];
        self.title = @"小助手";
    }else{
        self.startItem.title = @"关闭";
        self.title = @"启动中...";
        self.startItem.image = [UIImage systemImageNamed:@"tv.badge.wifi.fill"];
        [self.webServer start];
        [self refreshData];
    }
}

- (IBAction)setItemAction:(UIBarButtonItem *)sender {
    SetViewController *vc = [[SetViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)initWebServer {
    self.webServer = [[GCDWebUploader alloc] initWithUploadDirectory:[FilesManage documentsPath]];
    self.webServer.delegate = self;
    self.webServer.allowHiddenItems = YES;
    self.webServer.header = @"小助手";
    self.webServer.prologue = @"";
    self.webServer.epilogue = @"";
    self.webServer.footer = @"";
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 70;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.fileList.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    cell = [[[UINib nibWithNibName:@"TableViewCell" bundle:nil]instantiateWithOwner:self options:nil]lastObject];
    cell.backgroundColor = [UIColor systemGroupedBackgroundColor];
    cell.nameLab.lineBreakMode = NSLineBreakByTruncatingMiddle;
    cell.nameLab.text = self.fileList[indexPath.row];
    cell.sizeLab.text = [FilesManage getFileSize:self.fileList[indexPath.row]];
    cell.imageIV.image = [FilesManage getImage:self.fileList[indexPath.row]];
    return cell;
}

- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath*)indexPath  API_AVAILABLE(ios(11.0)) {

    UIContextualAction *sharRowAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal title:@"分享" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        [tableView setEditing:NO animated:YES];
        NSString *path = [NSString stringWithFormat:@"%@/%@",[FilesManage documentsPath],self.fileList[indexPath.row]];
        NSArray *activityItems = @[[NSURL fileURLWithPath:path]];
        UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
        UIActivityViewControllerCompletionWithItemsHandler myBlock = ^(UIActivityType __nullable activityType,
                                                                       BOOL completed, NSArray * __nullable returnedItems,
                                                                       NSError * __nullable activityError) {
            if (completed) {
                NSLog(@"completed");
            }
            else {
                NSLog(@"canceled");
            }
        };
        activityVC.completionWithItemsHandler = myBlock;
        [self presentViewController:activityVC animated:YES completion:nil];
        
    }];

    UIContextualAction *deleteRowAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal title:@"删除" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        [tableView setEditing:NO animated:YES];
        [FilesManage deleteFile:self.fileList[indexPath.row]];
        [FilesManage deleteDZMeBookRead:self.fileList[indexPath.row]];
        [self.fileList removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:(UITableViewRowAnimationFade)];
        
    }];
    sharRowAction.backgroundColor = [UIColor purpleColor];
    deleteRowAction.backgroundColor = [UIColor redColor];

    UISwipeActionsConfiguration *Configuration = [UISwipeActionsConfiguration configurationWithActions:@[sharRowAction,deleteRowAction]];
    return Configuration;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSString *path = [NSString stringWithFormat:@"%@/%@",[FilesManage documentsPath],self.fileList[indexPath.row]];
    
    if ([FilesManage isDirectory:path]) {
        NSLog(@"文件夹");
        return;
    }
    
    if ([path hasSuffix:@"txt"]) {
        
        if ([self.webServer isRunning]) {
            self.title = @"已关闭";
            [self.webServer stop];
        }
        
        [JXProgressHUD showLoadingWithMessage:@"解析中..."];
        __weak ViewController *weakSelf = self;
        NSString *urlStr = [NSString stringWithFormat:@"file://%@",path];
        NSURL *url = [NSURL URLWithString:urlStr];
        
        [DZMReadTextFastParser parserWithUrl:url completion:^(DZMReadModel * _Nonnull readModel) {
            
            [JXProgressHUD hideHUD];
            
            DZMReadController * read = [[DZMReadController alloc] init];
            
            read.readModel = readModel;
            
            [weakSelf.navigationController pushViewController:read animated:YES];
        }];
    } else if ([path hasSuffix:@"MOV"]) {
        ZFNormalViewController *vc = [[ZFNormalViewController alloc] init];
        NSString *urlStr = [NSString stringWithFormat:@"file://%@",path];
        vc.videoUrl = urlStr;
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        [self previewFile:path];
    }
}

#pragma mark - <GCDWebUploaderDelegate>
//上传文件到目录
- (void)webUploader:(GCDWebUploader*)uploader didUploadFileAtPath:(NSString*)path {
    [self refreshData];
}

- (void)webUploader:(GCDWebUploader*)uploader didDeleteItemAtPath:(NSString*)path{
    [self refreshData];
}

- (void)webServerDidCompleteBonjourRegistration:(GCDWebServer*)server {
    NSString *bonjour = [NSString stringWithFormat:@"%@", server.bonjourServerURL];
    bonjour = [bonjour stringByReplacingOccurrencesOfString:@"http://"withString:@""];
    bonjour = [bonjour stringByReplacingOccurrencesOfString:@".local/"withString:@""];
    self.title = bonjour;
}

-(void)refreshData {
    self.fileList = [NSMutableArray arrayWithArray:[FilesManage getAllFilesName]];
    [self.fileList removeObject:@"Inbox"];
    [self.tableView reloadData];
    self.spaceLab.text = [FilesManage usedSpaceAndfreeSpace];
}

-(void)previewFile:(NSString *)path {
    NSURL *filePath = [NSURL fileURLWithPath:path];
    UIDocumentInteractionController *documentController = [UIDocumentInteractionController interactionControllerWithURL: filePath];
    documentController.delegate = self;
    [documentController presentPreviewAnimated:YES];
}

//预览文件
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
    return self;
}

//将文件复制到Documents
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
    //获取授权
    BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource];
    if (fileUrlAuthozied) {
        //通过文件协调工具来得到新的文件地址，以此得到文件保护功能
        NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
        NSError *error;

        [fileCoordinator coordinateReadingItemAtURL:urls.firstObject options:0 error:&error byAccessor:^(NSURL *newURL) {
            //读取文件
            NSString *fileName = [newURL lastPathComponent];
            NSError *error = nil;
            if (error) {
                //读取出错
            } else {
                NSString *Doc = [[FilesManage documentsPath] stringByAppendingPathComponent:fileName];
                NSData *data = [NSData dataWithContentsOfURL:newURL];
                [data writeToFile:Doc atomically:YES];
                [self refreshData];
            }

            [self dismissViewControllerAnimated:YES completion:NULL];
        }];
        [urls.firstObject stopAccessingSecurityScopedResource];
    } else {
        //授权失败
    }
}

// 打开本地相册
-(void)openPhoto{
    //本地相册不需要检查，因为UIImagePickerController会自动检查并提醒
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:(UIImagePickerControllerSourceTypePhotoLibrary)];
    picker.delegate = self;
    picker.modalPresentationStyle = UIModalPresentationFullScreen;
    //设置选择后的图片可被编辑
    //picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"]){
        if (@available(iOS 11.0, *)) {
            NSURL *newURL = [info objectForKey:UIImagePickerControllerImageURL];
            NSString *fileName = [NSString stringWithFormat:@"%f.png",[[NSDate date] timeIntervalSince1970]];
            NSString *Doc = [[FilesManage documentsPath] stringByAppendingPathComponent:fileName];
            NSData *data = [NSData dataWithContentsOfURL:newURL];
            [data writeToFile:Doc atomically:YES];
            [self refreshData];
        }
        [picker dismissViewControllerAnimated:YES completion:^{}];
    }
}



//懒加载
- (UIDocumentPickerViewController *)documentPickerVC {
    if (!_documentPickerVC) {
        NSArray *documentTypes = @[@"public.content", @"public.text", @"public.source-code", @"public.image", @"public.audiovisual-content", @"com.adobe.pdf", @"com.apple.keynote.key", @"com.microsoft.word.doc", @"com.microsoft.excel.xls", @"com.microsoft.powerpoint.ppt", @"public.data"];
        _documentPickerVC = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeOpen];
        //设置代理
        _documentPickerVC.delegate = self;
        //设置模态弹出方式
        _documentPickerVC.modalPresentationStyle = UIModalPresentationFullScreen;
    }
    return _documentPickerVC;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:@"TableViewCell" bundle:nil] forCellReuseIdentifier:identifier];
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.backgroundColor = [UIColor systemGroupedBackgroundColor];
    }
    return _tableView;
}

- (void)dealloc
{
    [self removeNotification];
}

@end
